<?php

/**
 * video56.php 56视频模块
 *
 * @copyright			(C)2013 贵网
 * @URL					http://www.qbnews.cn/
 * @Author				王佳琦
 *
 */

defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin', 'admin', 0);
pc_base::load_sys_class('form', '', 0);
pc_base::load_app_func('global');
pc_base::load_app_class('api56', 'video56', 0);
class video56 extends admin {

    private $db;

    function __construct() {
        parent::__construct();
        $this->db = pc_base::load_model('video56_model');
    }

    /**
     * 视频管理
     */
    public function init() {
        $where = '';
        $page = $_GET['page'];
        $pagesize = 20;
        if($_GET['q']){
            if (isset($_GET['type'])) {
                if ($_GET['type']==1) {
                    $where .= ' `vid`=\''.$_GET['q'].'\'';
                } else {
                    $where .= " `subject` LIKE '%".$_GET['q']."%'";
                }
            }
        }
        
        if (isset($_GET['start_addtime']) && !empty($_GET['start_addtime'])) {
            $where .= !empty($where) ? ' AND `addtime`>=\''.strtotime($_GET['start_addtime']).'\'' : ' `addtime`>=\''.strtotime($_GET['start_addtime']).'\'';
        }
        if (!empty($_GET['end_addtime'])) {
            $where .= !empty($where) ? ' AND `addtime`<=\''.strtotime($_GET['end_addtime']).'\'' : ' `addtime`<=\''.strtotime($_GET['end_addtime']).'\'';
        }
        $infos = $this->db->listinfo($where, 'videoid DESC', $page, $pagesize);
        $pages = $this->db->pages;
        include $this->admin_tpl('video_list'); 
    }

    /**
     * 视频添加方法
     */
    public function add() {
        //读取配置文件
        $m_db = pc_base::load_model('module_model');
        $data = array();
        //更新模型数据库,重设setting 数据. 
        $data = $m_db->select(array('module'=>'video56'));
        $setting = string2array($data[0]['setting']);
        $params = array(
            'fields'   =>$setting['fields'],
            'sid'      =>$_SESSION['userid'],
            'css'      =>$setting['css'],
            'rurl'     =>$setting['rurl'],
            'ourl'     =>$setting['ourl'],
            'category' =>$_SESSION['pc_hash'],
        ); 

        include $this->admin_tpl('video_add');
    }

    /**
     * function edit
     * 视频编辑控制器
     */
    public function edit() {
        $videoid = intval($_GET['videoid']);
        if (!$videoid) showmessage('参数错误');
        if (isset($_POST['dosubmit'])) {
            $info = $this->db->get_one(array('videoid'=>$videoid));
            if($info['userupload']==0)  showmessage('非原创视频，不能更新！',HTTP_REFERER);
            $vid  = $_POST['vid'];
            $data = $_POST['data'];
            if (!$vid) showmessage('参数错误',HTTP_REFERER);
            if (!$data['subject']) showmessage('请填写视频名称',HTTP_REFERER);
            $rs = Open::Video_Update(array('vid'=>$vid,'title'=>$data['subject'],'desc'=>$data['content'],'desc'=>$data['content'],'tag'=>$data['tags']));
            
            if ($rs["errno"]) { //远程更新失败
               showmessage($rs["err"],HTTP_REFERER);
            }else{  // 远程更新成功，则写数据库
                if ($this->db->update($data,array('videoid'=>$videoid))) {  // 写数据库成功
                    showmessage('更新成功', 'index.php?m=video56&c=video56&a=init');
                }else{
                    showmessage('远程更新成功，但数据库写入失败' ,HTTP_REFERER);
                }
            }

        } else {
            $info = $this->db->get_one(array('videoid'=>$videoid));
            $adminDB = pc_base::load_model('admin_model');
            $admin = $adminDB->get_one(array('userid'=>$info['userid']),'username');
            include $this->admin_tpl('video_edit');
        }
    }

    /**
     * function delete
     * 删除视频控制器
     */
    public function delete() {
        $videoid = intval($_GET['videoid']);
        if (!$videoid) showmessage('参数错误');
        $r = $this->db->get_one(array('videoid'=>$videoid), 'vid,userupload');
        if (!$r) showmessage('要删除的视频不存在');
        if ($r["userupload"]) {
           $rs = Open::Video_Delete(array('vid'=>$r['vid']));
        }
        if ($this->db->delete(array('videoid'=>$videoid))) {
            showmessage('视频删除成功', HTTP_REFERER);
        }else{
            showmessage('视频删除失败', HTTP_REFERER);
        }

    }

    // 56视频导入
    public function import_56video(){
        pc_base::load_sys_class('format','',0);
        $c56      = isset($_GET['c56']) ? $_GET['c56'] : 0;
        $type     = isset($_GET['type']) ? $_GET['type'] : 'hot';
        $t        = isset($_GET['t']) ? $_GET['t'] : '';
        $keyword  = isset($_GET['keyword']) ? $_GET['keyword'] : '';
        $page     = isset($_GET['page']) ? $_GET['page'] : '1';
        $pagesize = 20;
        if ($keyword) { //搜索时

            //由于56接口参数不统一，所有这样转换下
            switch ($type) {
                case 'hot':
                    $s = 2;
                    break;
                case 'ding':
                    $s = 3;
                    break;
                case 'new':
                    $s = 1;
                    break;
                case 'share':
                    $s = 3;
                    break;
                case 'comment':
                    $s = 6;
                    break;
                default:
                    $s = 1;
                    break;
            }
            $params = array(
                'keyword' =>$keyword,
                // 'c'    =>$c56, 官方说给这个参数会有BUG
                'page'    =>$page,
                'rows'    =>$pagesize,
                't'       =>$t,
                's'       =>$s //1，最新上传（默认）2，浏览次数 3，相关程序 4，最多收藏 5，最高评分 6，时长 7，最多打分
                );
            $data = Open::Video_Search($params);
            $totals = $data["total"];
            unset($data["total"]);
            foreach ($data as $key => $value) {
                $list[$key]['Content'] = $value['content'];
                $list[$key]['Subject'] = $value['title'];
                $list[$key]['tag']     = $value['tag'];
                $list[$key]['id']      = $value['id'];
                $list[$key]['user_id'] = $value['user_id'];
                $list[$key]['img']     = $value['img'];
            }
        }else{
            $params = array(
                'type' =>$type,
                'c'    =>$c56,
                't'    =>$t,
                'page' =>$page,
                'rows' =>$pagesize
            );
            $data   = Open::Video_All($params);
            $totals = $data["total"];
            $list   = $data["data"];
        }
        //var_dump($list);
        include $this->admin_tpl('import_56video'); 
    }
    // 预览导入56视频列表中的视频
    public function preview_56video(){
        $vid = $_GET['vid'];
        $app = include dirname(__FILE__).'/classes/sdk56/conf.php';
        include $this->admin_tpl('priview_56video');
    }

    // 导入56视频入库
    public function doimport(){
        $ids = $_POST['ids'];
        if (!is_array($ids)) showmessage('您没有勾选信息', HTTP_REFERER);
        $app        = include dirname(__FILE__).'/classes/sdk56/conf.php';
        $userid     = $_SESSION['userid'];
        $importdata = $_POST["importdata"];
        foreach ($ids as $i) {
            $data['userid']     = $userid;
            $data['vid']        = $importdata[$i]['vid'];
            $data['subject']    = $importdata[$i]['subject'];
            $data['content']    = $importdata[$i]['content'];
            $data['tags']       = $importdata[$i]['tags'];
            $data['cover']      = $importdata[$i]['cover'];
            $data['forbid']     = 'n';
            $data['chk']        = 'y';
            $data['userupload'] = 0;
            $data['addtime']    = time();
            $data['player']     = 'http://player.56.com/'.$app['appkey'].'/open_'.$importdata[$i]['vid'].'.swf';
            $this->db->insert($data);
        }
        showmessage('视频导入完成', HTTP_REFERER);

    }

    // 模块配置
    public function setting(){
        $m_db = pc_base::load_model('module_model');
        if(isset($_POST['dosubmit'])) {
            if(is_array($_POST['fields'])){
              $_POST['setting']['fields'] = implode(',',$_POST['fields']);
            }else{
                $_POST['setting']['fields'] = 'title,content,tags';
            }

            //保存接口配置
            $app = $_POST["app"];
            if (is_array($app)) {
                arr2file(dirname(__FILE__).'/classes/sdk56/conf.php', $app);
            }

            //更新模型数据库,重设setting 数据. 
            $setting = array2string($_POST['setting']);
            $m_db->update(array('setting'=>$setting),array('module'=>'video56'));
            showmessage('设置成功',HTTP_REFERER);
        } else {
            //读取配置文件
            $data = array();
            //更新模型数据库,重设setting 数据. 
            $data = $m_db->select(array('module'=>'video56'));
            $setting = string2array($data[0]['setting']);
            $fields = explode(',', $setting['fields']);

            //读取接口配置
            $app = include dirname(__FILE__).'/classes/sdk56/conf.php';

            include $this->admin_tpl('video_setting');
        }
    }

    // 视频预览
    public function public_view_video(){
        $id = intval($_GET['id']);
        if (!$id) showmessage('请选择要浏览的视频！');
        $info = $this->db->get_one(array('videoid'=>$id), 'player');
        include $this->admin_tpl('view_video');
    }




}
